package tako.wisers.com.android.apis.location;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;

public class LocationDecord {
	public static final int addressNameNum = 3;

	private Geocoder coder;
	private String mLocationName;
	private String countryCode;
	private String zh_code = "CN|HK|TW";
	private Context context;
	private double lat;
	private double lon;
	private static Locale currentLocale = Locale.ENGLISH; 

	public LocationDecord(Context context) {
		this.context = context;
		coder = new Geocoder(context, currentLocale);
	}

	public void executePoint(double lat, double lon) {
		try {
			List<Address> adrList = coder.getFromLocation(lat, lon,5);
			int i = 0;
			String countryName = "";
			String adminArea = "";
			String LocalityName = "";
			String Thoroughfare = "";
			for (Address a : adrList) {
				String countryCode = a.getCountryCode();
				if(changeLocale(lat, lon, countryCode) && i < 1) return;
				if(countryName.equals("") && a.getCountryName() != null){
					countryName = a.getCountryName();
				} 
				if(adminArea.equals("") && a.getAdminArea() != null){
					adminArea = a.getAdminArea();
				}
				if(LocalityName.equals("") && a.getLocality() != null){
					LocalityName = a.getLocality();
				}
				if(Thoroughfare.equals("") && a.getThoroughfare() != null){
					Thoroughfare = a.getThoroughfare();
				}
				if(!countryName.equals("") && !adminArea.equals("") && !LocalityName.equals("") && !Thoroughfare.equals("") ){
					break;
				}
				i++;
			}
			this.mLocationName = LocalityName + " " + adminArea + " " + countryName;
			this.lat = lat;
			this.lon = lon;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private boolean changeLocale(double lat, double lon, String countryCode) {
		if(zh_code.contains(countryCode) && !currentLocale.equals(Locale.CHINESE)){
			return setLocate(lat, lon, Locale.CHINESE);
		}else if(!zh_code.contains(countryCode) && !currentLocale.equals(Locale.ENGLISH)){
			return setLocate(lat, lon, Locale.ENGLISH);
		}
		return false;
	}

	private boolean setLocate(double lat, double lon, Locale locate) {
		currentLocale = locate;
		coder = new Geocoder(context, currentLocale);
		executePoint(lat, lon);
		return true;
	}
	
	public String getLocationName() {
		return mLocationName;
	}

	public String getCountryCode() {
		return countryCode;
	}

	public double getLat() {
		return lat;
	}

	public double getLon() {
		return lon;
	}
	
	public Address getLocationByName(String name){
		try {
			List<Address> addressList = coder.getFromLocationName(name, 1);
			if(addressList != null && addressList.size() > 0){
				return addressList.get(0);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
}
